package qj.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SqlUtil {
	public static final int ODBC = 0;
	private static final Pattern ptn_selectSQL = Pattern.compile("^[\\s(]*SELECT", Pattern.CASE_INSENSITIVE);
	public static boolean isSelectSQL(String sql) {
		Matcher m = ptn_selectSQL.matcher(sql);
		return m.find();
	}

	public static Connection open(String dbString, int type) throws SQLException {
		String driverClass;

		switch (type) {
		case ODBC:
			driverClass = "sun.jdbc.odbc.JdbcOdbcDriver";
			dbString = "jdbc:odbc:" + dbString;
			break;
		default:
			throw new RuntimeException("Unknow db type");
		}
		
		try {
			Class.forName(driverClass);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException("DB driver class not found: " + driverClass);
		}
		
		return DriverManager.getConnection(dbString);
	}

	public static String getInsertPlaceHolder(int count) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < count; i++) {
			if (i > 0)
				sb.append(", ");
			sb.append("?");
		}
		String result = sb.toString();
		return result;
	}
}
